<?php

namespace App\Http\Controllers\Admin\Service;

use App\Http\Controllers\Controller;
use App\Http\Requests\service\AbnormalRequest;
use App\Models\DepotBanModel;
use App\Models\DictionaryModel;
use App\Models\DispatchLoadListModel;
use App\Models\DispatchTaskModel;
use App\Models\OrderModel;
use App\Models\service\AbnormalConfigModel;
use App\Models\service\AbnormalModel;
use App\Models\service\ProblemModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CardData extends Controller
{

    /**
     * Notes:列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $containerID = $request->input('containerID', '');
        $code = $request->input('code', '');
        $ban_id = $request->input('ban_id', '');
        $route_id = $request->input('route_id', '');
        $airline_flight_id = $request->input('airline_flight_id', '');
        $startTime = $request->input('startTime', '');
        $endTime = $request->input('endTime', '');

        if($containerID){
            $containerID = explode(',', $containerID);
        }

        if($code){
            $code = explode(',', $code);
        }

        $query = DepotBanModel::whereHas('container', function ($query) use ($containerID, $code, $ban_id) {
            if($containerID){
                $query->whereIn('container_id', $containerID);
            }
            if($ban_id){
                $query->where('ban_id', $ban_id);
            }
            $query->whereHas('code', function ($query) use ($code){
                if($code){
                    $query->whereIn('code', $code);
                }
            });
        })->whereHas('flight', function ($query) use ($startTime, $endTime, $route_id, $airline_flight_id) {
            if($startTime && $endTime){
                $query->whereBetween('take_off_time', [$startTime, $endTime]);
            }
            if($route_id || $airline_flight_id){
                $query->whereHas('flight_lines', function ($query) use ($route_id, $airline_flight_id){
                    if($route_id){
                        $query->where('route_id', $route_id);
                    }
                    if($airline_flight_id){
                        $query->where('airline_flight_id', $airline_flight_id);
                    }
                });
            }
        })->with(['container' => function ($query) {
            $query->with(['code', 'ban']);
        },
            'flight' => function ($query) {
                $query->with(['flight_lines' => function ($query) {
                    $query->with(['route', 'destination', 'air_line']);
                }]);
            }
        ]);


        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $order_count = $item->items->count();
            $big_count = $item->items->sum('nums');
            $total_weight = $item->items->sum('weight');

            $order_ids = $item->items->pluck('order_id');
            $take_order_count = OrderModel::whereIn('id', $order_ids)->groupBy('take_order_id')->count();
            $total_volume  = OrderModel::whereIn('id', $order_ids)->sum('pre_volume');

            $flight_lines = $item->flight->items;

            $flight_lines_arr = [];
            if($flight_lines){
                $flight_lines_arr = $flight_lines->map(function($item){
                    return [
                        'route_name' => $item->route->name ?? '',
                        'destination_name' => $item->destination->name ?? '',
                        'flight_number' => $item->air_line->flight_number ?? ''
                    ];
                });
                $flight_lines_arr = $flight_lines_arr->toArray();
            }
            $res = [
                'id' => $item->id,
                'containerID' => $item->container->container_id ?? '',
                'ban_name' => $item->container->ban->name ?? '',
                'code' => $item->container->code->code ?? '',
                'flight_number' => $flight_lines_arr ? implode('，', array_column($flight_lines_arr, 'flight_number')) : '',
                'route_name' => $flight_lines_arr ? implode('，', array_column($flight_lines_arr, 'route_name')) : '',
                'total_volume' => $total_volume,
                'total_weight' => $total_weight,
                'take_order_count' => $take_order_count,
                'order_count' => $order_count,
                'big_count' => $big_count,
                'take_off_time' => $item->flight->take_off_time ?? '',
                'created_at' => $item->created_at->toDateTimeString(),
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }



    public function detail(Request $request)
    {
        $id = $request->input('id');
        $depot_ban = DepotBanModel::find($id);
        if(!$depot_ban){
            return $this->error('数据不存在');
        }

        $flight_lines = $depot_ban->flight->items;

        $flight_lines_arr = [];
        if($flight_lines){
            $flight_lines_arr = $flight_lines->map(function($item){
                return [
                    'route_name' => $item->route->name ?? '',
                    'destination_name' => $item->destination->name ?? '',
                    'flight_number' => $item->air_line->flight_number ?? ''
                ];
            });
            $flight_lines_arr = $flight_lines_arr->toArray();
        }

        $return = [
            'id' => $depot_ban->id,
            'route_name' => $flight_lines_arr ? implode('，', array_column($flight_lines_arr, 'route_name')) : '',
            'destination_name' => $flight_lines_arr ? implode('，', array_column($flight_lines_arr, 'destination_name')) : '',
            'flight_number' => $flight_lines_arr ? implode('，', array_column($flight_lines_arr, 'flight_number')) : '',

        ];

        $items = $depot_ban->items;
        $items_arr = [];
        if($items){
            $items_arr = $items->map(function($item) use ($depot_ban){
                $split_order = $item->order->split_order;
                $split_order_sn = '';
                if($split_order){
                    $sns = $split_order->pluck('sn');
                    $split_order_sn = implode('，', $sns);
                }

                $task_list = DispatchLoadListModel::where('order_id', $item->order_id)->first();
                $car_number = '';
                if($task_list){
                    $task = DispatchTaskModel::find($task_list->dispatch_task_id);
                    if($task){
                        $car_number = $task->car->car_number ?? '';
                    }
                }

                $packages_name = DictionaryModel::whereIn('id', explode(',', ($item->order->packages ?? [])))
                    ->pluck('name');

                return [
                    'customer_name' => $item->order->customer->name ?? '',
                    'customer_sn' => $item->order->customer->sn ?? '',
                    'customer_type' => $item->order->customer->customer_type->name ?? '',
                    'take_order_sn' => $item->order->take_order->sn ?? '',
                    'split_order_sn' => $split_order_sn,
                    'hk_sn' => $item->order->hk_sn ?? '',
                    'packages' => $packages_name,
                    'jd_color' => $item->order->goods_label ?? '',
                    'goods_attr' => OrderModel::GOODS_ATTR_MAPS[$item->order->goods_attr] ?? '',
                    'car_date' => $depot_ban->created_at->toDateTimeString(),
                    'volume' => $item->order->pre_volume ?? 0,
                    'volume_weight' => ($item->order->pre_volume ?? 0) * 166.67,
                    'storage_weight' => $item->weight,
                    'car_number' => $car_number
                ];
            });
            $items_arr = $items_arr->toArray();
        }

        $return['list'] = $items_arr;

        return $this->success($return);
    }


}
